﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ThoiTrang.Business;
using ThoiTrang.Entities;


public partial class Admin_article_list : System.Web.UI.Page
{
    public  string ckid="";

    protected void Page_Load(object sender, EventArgs e)
    {
        //HtmlGenericControl js = new HtmlGenericControl("script");
        //js.Attributes.Add("type", "text/javasript");
        //js.Attributes.Add("src", "js/tooltip.js");
        //Page.Header.Controls.Add(js);


        //HtmlGenericControl css = new HtmlGenericControl("link");
        //css.Attributes.Add("rel", "stylesheet");
        //css.Attributes.Add("type", "text/css");
        //css.Attributes.Add("href", "css/tooltip.css");
        //Page.Header.Controls.Add(css);

        if (!IsPostBack)
        {
            a_Session ss = null;
            a_User usr = null;
            a_UserType usrType = null;
            //if (SessionManager.IsLogged)
            //{
            ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
            ckid = ss.SessionID;
            usr = a_UserService.Geta_User(ss.CookieID);
            usrType = a_UserTypeService.Geta_UserType(usr.UserTypeID);
            //}
            //else
            //{
            //    Response.Redirect("~/login.aspx");
            //}

            switch (usrType.AccessLevel)
            {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
            }
            ltrWellcome.Text = "Hi " + usr.Firstname + " " + usr.Lastname;

            

            txtDateFrom.Text = DateTime.Now.Subtract(new TimeSpan(1000, 0, 0, 0)).ToString("dd - MM - yyyy");
            txtDateTo.Text = DateTime.Now.ToString("dd - MM - yyyy");
            loadMainCat(new DataTable());
            loadSubCat();
            bindSeachBeforeLoadData();
            
            LoadData();
            LoadTitle();
        }
    }

    void LoadTitle()
    {
        string st = Request.QueryString["st"] == null ? "0" : Request.QueryString["st"];

        btnApproved.Visible = true;        
        btnMakeFeatured.Visible = true;
        btnPrivate.Visible = true;        
        btnResetArticle.Visible = true;
        
        switch (st)
        {
            case "0":
                ltrTitle.Text = "Article Pending";
                grvSearchResult.Columns[6].Visible = false;
                btnResetArticle.Visible = false;
                break;
            case "1":
                
                ltrTitle.Text = "Article Approved";
                grvSearchResult.Columns[6].Visible = false;
                btnApproved.Visible = false;
                btnResetArticle.Visible = false;
                if (Request.QueryString["isfea"] != null)
                {
                    grvSearchResult.Columns[6].Visible = true;
                    btnPrivate.Visible = false;
                    btnResetArticle.Visible = true;
                    btnApproved.Visible = true;
                    ltrTitle.Text = "Article Featured";
                }
                break;
        }
    }

    void loadMainCat(DataTable dtb )
    {
        //loadMainCat(searchRes.Tables[2]);
        ddlMainCat.DataTextField = a_CatMainColumns.UName.ToString();
        ddlMainCat.DataValueField = a_CatMainColumns.CatID.ToString();
        ddlMainCat.DataSource = ThoiTrang.Business.a_CatMainService.Geta_CatMainList(a_CatMainColumns.UName, ThoiTrang.Data.OrderDirection.ASC);
        ddlMainCat.DataBind();
        ddlMainCat.Items.Insert(0, new ListItem("Tất cả", ""));
    }

    void loadSubCat()
    {
        //if (ddlMainCat.Items.Count > 0)
        //{
        string cat = Request.QueryString["cat"] == null ? "" : Request.QueryString["cat"];
        if (cat != "")
        {
            try
            {
                if (Convert.ToInt32(cat) > 0)
                {
                    ddlMainCat.SelectedValue = cat;
                    ddlSubCat.DataTextField = a_CatSubColumns.UName.ToString();
                    ddlSubCat.DataValueField = a_CatSubColumns.SubCatID.ToString();
                    ddlSubCat.DataSource = null;
                    if (ddlMainCat.SelectedValue == "")
                    {
                        ddlSubCat.Items.Clear();
                    }
                    else
                    {
                        ddlSubCat.DataSource = ThoiTrang.Business.a_CatSubService.Geta_CatSubListByCatMain(
                            Convert.ToInt32(ddlMainCat.SelectedValue));
                    }
                    ddlSubCat.DataBind();
                    ddlSubCat.Items.Insert(0,new ListItem(" All ","0"));
                }
            }
            catch { }
        }
        //}
    }

    void doSearch()
    {
        int mainCat = 0;
        int subCat = 0;
        string query = "";
        try
        {
            mainCat = Convert.ToInt32(ddlMainCat.SelectedValue == "" ? "0" : ddlMainCat.SelectedValue);
            query += "cat=" + mainCat.ToString();
        }
        catch { }
        try
        {
            subCat = Convert.ToInt32(ddlSubCat.SelectedValue == "" ? "0" : ddlSubCat.SelectedValue);
            query += "&subcat=" + subCat.ToString();
        }
        catch { }

        string status = "";// 0: pending  1: approved
        string feature = "";
        int page = 1;

        status = Request.QueryString["st"] == null ? "" : Request.QueryString["st"];
        query += "&st=" + status;
        page = Convert.ToInt32(Request.QueryString["p"] == null ? "1" : Request.QueryString["p"]);
        feature = Request.QueryString["isfea"] == null ? "0" : Request.QueryString["isfea"];
        query += "&isfea=" + feature;
        query += "&searchby=" + ddlSearchBy.SelectedValue;
        query += "&key=" + HttpUtility.UrlDecode(txtSearchBy.Text.Trim());
        query += "&datefrom=" + HttpUtility.UrlDecode(txtDateFrom.Text);
        query += "&dateto=" + HttpUtility.UrlDecode(txtDateTo.Text);
        query += "&sortby=" + ddlSortBy.SelectedValue;
        query += "&orderby=" + ddlSortOrder.SelectedValue;
        query += "&ckid="+ SessionManager.GetCookie();

        Response.Redirect("~/Admin/adm_article_list.aspx?" + query.Trim('&'));
    }

    void bindSeachBeforeLoadData()
    {
        ddlMainCat.SelectedValue = Request.QueryString["cat"] == null ? "" : Request.QueryString["cat"];
        ddlSubCat.SelectedValue = Request.QueryString["subcat"] == null ? "" : Request.QueryString["subcat"];
        ddlSearchBy.SelectedValue = Request.QueryString["searchby"] == null ? "UTitle" : Request.QueryString["searchby"];
        txtSearchBy.Text = Request.QueryString["key"] == null ? "" : Request.QueryString["key"];
        txtDateFrom.Text = Request.QueryString["datefrom"] == null ? "01 - 01 - 2006" :HttpUtility.UrlDecode(  Request.QueryString["datefrom"]);
        txtDateTo.Text = Request.QueryString["dateto"] == null ? DateTime.Now.ToString("dd - MM - yyyy") : HttpUtility.UrlDecode( Request.QueryString["dateto"]);
        ddlSortBy.SelectedValue = Request.QueryString["sortby"] == null ? "" : Request.QueryString["sortby"];
        ddlSortOrder.SelectedValue = Request.QueryString["orderby"] == null ? "" : Request.QueryString["orderby"];
    }

    private void LoadData()
    {
        int mainCat = 0;
        int subCat = 0;
        string query = "";
        try
        {
            mainCat = Convert.ToInt32(ddlMainCat.SelectedValue == "" ? "0" : ddlMainCat.SelectedValue);
            query += "cat=" + mainCat.ToString();
        }
        catch { }
        try
        {
            subCat = Convert.ToInt32(ddlSubCat.SelectedValue == "" ? "0" : ddlSubCat.SelectedValue);
            query += "&subcat=" + subCat.ToString();
        }
        catch { }

        string status = "";// 0: pending  1: approved
        string feature = "";
        int page = 1;

        status = Request.QueryString["st"] == null ? "" : Request.QueryString["st"];
        query+="&st="+status;
        page = Convert.ToInt32(Request.QueryString["p"] == null ? "1" : Request.QueryString["p"]);
        feature = Request.QueryString["isfea"] == null ? "0" : Request.QueryString["isfea"];
        query += "&isfea=" + feature;
        query += "&searchby=" + ddlSearchBy.SelectedValue;
        query += "&key="+HttpUtility.UrlEncode( txtSearchBy.Text.Trim());
        query += "&datefrom=" + HttpUtility.UrlEncode(txtDateFrom.Text);
        query += "&dateto=" + HttpUtility.UrlEncode(txtDateTo.Text);
        query += "&sortby=" + ddlSortBy.SelectedValue;
        query += "&orderby=" + ddlSortOrder.SelectedValue;

        int totalRecord = 0;

        a_User myUser = null;
        a_Session ss = null;
        a_UserType usrType = null;
        //if (SessionManager.IsLogged)
        //{
            ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
            myUser = a_UserService.Geta_User(ss.CookieID);
            usrType = a_UserTypeService.Geta_UserType(myUser.UserTypeID);
        //}
        //else { return; }

        DataSet searchRes = new DataSet();

        string dtF = txtDateFrom.Text.Split('-')[2] + "-" + txtDateFrom.Text.Split('-')[1] + "-" + txtDateFrom.Text.Split('-')[0];

        string dtT = txtDateTo.Text.Split('-')[2] + "-" + txtDateTo.Text.Split('-')[1] + "-" + txtDateTo.Text.Split('-')[0];


        searchRes = ThoiTrang.Business.a_ArticleService.Get_Articles_selListByConditionAmdin(
            ss.CookieID,
            usrType.AccessLevel,
            feature.ToString(),
            status.ToString(),
            20, 6,
            ddlSearchBy.SelectedValue, HttpUtility.UrlDecode(txtSearchBy.Text.Trim()),
            Convert.ToDateTime(dtF).ToString(FOConstants.DBDateTimeFormat),
            Convert.ToDateTime(dtT).ToString(FOConstants.DBDateTimeFormat),
            ddlSortBy.SelectedValue, ddlSortOrder.SelectedValue,
            page,
            ddlMainCat.SelectedValue, ddlSubCat.SelectedValue
            );

        if (searchRes.Tables.Count < 2)
        {
            grvSearchResult.DataSource = null;
            ltrStatic.Text = "No record found for this period.";
            ltrPaging.Visible = false;            
        }
        else
        {
                                  

            //data table for paging
            DataTable dtb = searchRes.Tables[0];

            totalRecord = (int)dtb.Rows[0]["TotalRecords"];
            int recPerPage = 20;// (int)dtb.Rows[0]["PageSize"];
            int pageSet = 6;// (int)dtb.Rows[0]["PageSetSize"];

            //AdminPaging1.Total = totalRecord;

            ltrPaging.Visible = true;
            ltrStatic.Text = "Page " + page.ToString() + "/" + dtb.Rows[0]["TotalPages"].ToString() + "&nbsp;&nbsp;&nbsp;&nbsp;"+ totalRecord.ToString()+" records.";
            ltrPaging.Text = CommonFunc.QueryPaging(page, Convert.ToInt32(totalRecord / recPerPage) + 1, pageSet);
            grvSearchResult.DataSource = searchRes.Tables[1];
            AdminPaging1.Total = totalRecord;
            ltrPaging.Visible = false;
        }
     
       grvSearchResult.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
       // LoadData();  
        doSearch();
    }
    protected void btnFillter_Click(object sender, EventArgs e)
    {
        //LoadData();
        doSearch();
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect(HttpContext.Current.Request.Url.ToString());
    }
    protected void btnPrivate_Click(object sender, EventArgs e)
    {
        a_User myUser = null;
        a_Session ss = null;
        a_UserType usrType = null;
        //if (SessionManager.IsLogged)
        //{
        ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
        myUser = a_UserService.Geta_User(ss.CookieID);
        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            Literal ltr = (Literal)r.FindControl("ltrIDA");
            if (chk.Checked)
            {
                string key = ltr.Text;
                a_Article aa = a_ArticleService.Geta_Article(Convert.ToInt32(key));
                aa.PublishDate = DateTime.Now;
                aa.Permission = true;
                aa.PostBy_UserID = myUser.UserID;
                a_ArticleService.Updatea_Article(aa);
            }
        }
        LoadData();
    }
    protected void btnApproved_Click(object sender, EventArgs e)
    {
        a_User myUser = null;
        a_Session ss = null;
        a_UserType usrType = null;
        //if (SessionManager.IsLogged)
        //{
        ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
        myUser = a_UserService.Geta_User(ss.CookieID);

        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            Literal ltr = (Literal)r.FindControl("ltrIDA");
            if (chk.Checked)
            {
                string key = ltr.Text;
                a_Article aa = a_ArticleService.Geta_Article(Convert.ToInt32(key));
                aa.PublishDate = DateTime.Now;
                aa.PublishStatus = true;
                aa.PostBy_UserID = myUser.UserID;
                a_ArticleService.Updatea_Article(aa);
            }
        }
        LoadData();
    }
    protected void btnMakeFeatured_Click(object sender, EventArgs e)
    {
        a_User myUser = null;
        a_Session ss = null;
        a_UserType usrType = null;
        //if (SessionManager.IsLogged)
        //{
        ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
        myUser = a_UserService.Geta_User(ss.CookieID);
        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            Literal ltr = (Literal)r.FindControl("ltrIDA");
            if (chk.Checked)
            {
                string key = ltr.Text;
                a_Article aa = a_ArticleService.Geta_Article(Convert.ToInt32(key));
                aa.IsFeatured = true;
                aa.PostBy_UserID = myUser.UserID;
                a_ArticleService.Updatea_Article(aa);
            }
        }
        LoadData();
    }

    protected void btnResetArticle_Click(object sender, EventArgs e)
    {
        a_User myUser = null;
        a_Session ss = null;
        a_UserType usrType = null;
        ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
        myUser = a_UserService.Geta_User(ss.CookieID);
        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            Literal ltr = (Literal)r.FindControl("ltrIDA");
            if (chk.Checked)
            {
                string key = ltr.Text;// grvSearchResult.DataKeys[r.RowIndex].Value.ToString();
                a_Article aa = a_ArticleService.Geta_Article(Convert.ToInt32(key));
                aa.IsFeatured = false;
                aa.PostBy_UserID = myUser.UserID;
                a_ArticleService.Updatea_Article(aa);
            }
        }
        LoadData();
    }

    protected void btnUploadFeatureImage_Click(object sender, EventArgs e)
    {
        string url = "adm_articleFeatured_upload.aspx?ckid="+ Request.QueryString["ckid"];
        Response.Redirect(url);
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            if (chk.Checked)
            {
                string key= grvSearchResult.DataKeys[r.RowIndex].Value.ToString();
                a_ArticleService.Deletea_Article(Convert.ToInt32(key));
            }
        }
        LoadData();
    }
    protected void ddlMainCat_SelectedIndexChanged(object sender, EventArgs e)
    {
        //loadSubCat();
        //string url = Request.Url.ToString();
        doSearch();
    }
    /*
    public static string Paging(int totalRecord, int recPerPage, int pageSet)
    {
        string currentUrl = HttpContext.Current.Request.Url.ToString();

        int currentPage = HttpContext.Current.Request.QueryString["p"] == null ? 1 : Convert.ToInt32(HttpContext.Current.Request.QueryString["p"]);
        int prePage = currentPage == 1 ? 1 : currentPage - 1;
        int nextPage = currentPage + 1;
        int lastPage =totalRecord / recPerPage +1;
        
        string []parseUrl=currentUrl.Split('?');

        currentUrl = parseUrl[0];
        string currentParam = "";
        
        if (parseUrl.Length > 1)
        {
            string[] urlParam = {};
            urlParam = parseUrl[1].Split('&');
            for (int i = 0; i < urlParam.Length; i++)
            {
                if(urlParam[i].IndexOf("p=")<0)   currentParam += urlParam[i]+"&";
            }
            currentParam = currentParam.Trim('&');
        }
        
        string paging = "<table class='p3 fr'><tr>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=1&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_previousset_off.gif'/></a></td>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + prePage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_previouspage_off.gif'/></a></td>";

        if (currentPage > pageSet)
        {
        }
        else
        {
            for (int i = 1; i < currentPage; i++)
            {
                paging += "<td class='go'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
            }
        }
        
        for (int i = currentPage; i < currentPage+pageSet; i++)
        {
            if (i==currentPage)
                paging += "<td class='current'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
            else
                paging += "<td class='go'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
        }

        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + nextPage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_nextpage_on.gif'/></a></td>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + lastPage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_nextset_off.gif'/></a></td>";
        paging += "</tr></table>";

        return paging;
    }
*/   
}
